
/*    This file is part of the Managarm operating system.
 *   Copyright (C) 2007, 2008, 2009  Alexander van der Grinten
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

package org.managarm.jmanacclib.frontend.korona;

import java.util.HashMap;

import org.managarm.jmanacclib.core.CclibUnit;
import org.managarm.jmanacclib.core.CclibException;

public class KorIdentTree {
	private final HashMap<Character, KorIdentTree> children
			= new HashMap<Character, KorIdentTree>();
	private final Character character;
	private final KorIdentTree parent;
	private Object object;
	
	public KorIdentTree() {
		this(null, null); // creates the root object
	}
	public KorIdentTree(KorIdentTree parent,
			Character character) {
		this.parent = parent;
		this.character = character;
	}
	
	public void insert(String string, Object object,
			CclibUnit curunit, int curline)
			throws CclibException {
		// find / create the subtree that contains 
		KorIdentTree tree = this;
		for(int i = 0; i < string.length(); i++) {
			final Character c = string.charAt(i);
			
			// find / create the subtree that contains c
			if(tree.children.containsKey(c)) {
				tree = tree.children.get(c);
			}else{
				final KorIdentTree subtree
						= new KorIdentTree(this, c);
				tree.children.put(c, subtree);
				tree = subtree;
			}
		}
		
		if(tree.object != null)
			throw new CclibException("Identifier: '"
					+ string + "' already in use", curunit, curline);
		tree.object = object;
	}
	
	public void remove(String string) {
		// get the tree node that represents the string
		KorIdentTree tree = this;
		for(int i = 0; i < string.length(); i++) {
			final Character c = string.charAt(i);
			
			if(tree.children.containsKey(c) == false)
				return; // this tree does not contain the string
			tree = children.get(c);
		}
		
		if(tree != null)
			tree.destroy();
	}
	
	public boolean containsChild(Character c) {
		return children.containsKey(c);
	}
	public KorIdentTree getChild(Character c) {
		return children.get(c);
	}
	public Object getObject() {
		return object;
	}
	
	private void destroy() {
		object = null;

		// remove this tree node from the parent node
		if(parent != null && children.size() == 0)
			parent.children.remove(character);
	}
}
